package kuang.producer_consumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Test2 {

    public static void main(String[] args) {
        Data2 data = new Data2();

        new Thread(() -> {
            try {
                for(int i = 0; i < 10; i++){
                    data.increment();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "producer").start();

        new Thread(() -> {
            try {
                for(int i = 0; i < 10; i++){
                    data.decrement();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "consumer").start();

        new Thread(() -> {
            try {
                for(int i = 0; i < 10; i++){
                    data.increment();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "producer2").start();

        new Thread(() -> {
            try {
                for(int i = 0; i < 10; i++){
                    data.decrement();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "consumer2").start();

    }
}


class Data2{

    private int number = 0;

    //lock替代 synchronized
    Lock lock = new ReentrantLock();
    //lock的监视器，取代 wait、notify、notifyAll
    //condition.await();  代替 wait
    //condition.signalAll(); 代替 notifyAll
    Condition condition = lock.newCondition();

    //public void increment() throws InterruptedException {
    //    lock.lock();
    //    try {
    //
    //        //业务代码++++
    //    } catch (InterruptedException e) {
    //        e.printStackTrace();
    //    } finally {
    //        lock.unlock();
    //    }
    //}

    public void increment() throws InterruptedException {
        lock.lock();
        try {
            while(number != 0){
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "-->" + number);
            //通知其他线程
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public  void decrement() throws InterruptedException {
        lock.lock();
        try {
            while(number == 0){
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "-->" + number);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
